package com.jcbase.controller;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;
import com.jcbase.core.auth.interceptor.AuthorityInterceptor;
import com.jcbase.core.auth.interceptor.SysLogInterceptor;
import com.jcbase.core.util.DateUtils;
import com.jcbase.core.util.FileUtils;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;

/**
 * @category 上传控制器
 * 
 * @author yiz
 * @date 2016年7月27日 下午7:56:40
 * @version 1.0.0 
 * @copyright pycredit.cn
 */
@Clear({ AuthorityInterceptor.class, SysLogInterceptor.class })
public class UploadController extends Controller {
	private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
	public static final int BUFFER_SIZE = 2 * 1024 * 1024;

	public void index() {
		renderText("OK");
	}

	/**
	 * @category 图片上传
	 */
	public void uploadImg() {
		String dataStr = DateUtils.format(new Date(), "yyyyMMddHHmm");
		List<UploadFile> flist = this.getFiles("/temp", 1024 * 1024 * 50);
		Map<String, Object> data = Maps.newHashMap();
		if (flist.size() > 0) {
			UploadFile uf = flist.get(0);
			String status_url = PropKit.get("static_url");
			String fileUrl = "img/" + dataStr + "/" + uf.getFileName();
			String newFile = PathKit.getWebRootPath() + PropKit.get("uploadPath") + fileUrl;
			logger.debug("文件上传路径newFile=" + newFile);
			FileUtils.mkdir(newFile, false);
			FileUtils.copy(uf.getFile(), new File(newFile), BUFFER_SIZE);
			uf.getFile().delete();
			data.put("staticUrl", status_url);
			data.put("fileUrl", fileUrl);
			data.put("code", "1");
		} else {
			data.put("code", "0");
		}
		renderJson(data);
	}

}
